package st.business.tepth.business.user.busnumber.workholder.maintain.work.content;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import st.business.tepth.base.OnDataConvertListener;
import st.business.tepth.business.bean.MaintainNotCompleteBean;
import st.business.tepth.business.bean.PickGoods;
import st.business.tepth.business.bean.RepairTaskTypeBean;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-03-23 09:46
 */

public class MaintainWorkModel implements MaintainWorkContract.Model {

    @Override
    public Disposable getWorkData(String token, int repairId, int vehicleSeriesId,
                                  final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.GetMyRepairTask)
                .params("repairId", repairId)
                .params("token", token)
                .params("vehicleSeriesId", vehicleSeriesId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertToBusRepairInfo(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                    }
                })
                .build()
                .get();
    }

    @Override
    public Disposable commitProgram(final String token, final int repairId, int repairTaskId,
                                    final int vehicleSeriesId, String taskItemList,
                                    String maintenanceOperationList,
                                    final OnDataConvertListener<List<PickGoods>> pickListener,
                                    final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.MaintainProgramAll)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .params("taskItemList", taskItemList)
                .params("maintenanceOperationList", maintenanceOperationList)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            String object = jsonObject.getString("data");
                            if (pickListener != null) {
                                pickListener.convert(convertToPickGoods(object));
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }

                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            listener.convert(convertToBusRepairInfo(object));
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable submitFinishWork(final String token, final int repairId,
                                       int repairTaskId, final int vehicleSeriesId,
                                       final OnDataConvertListener<RepairTaskTypeBean> dataListener,
                                       final OnDataConvertListener<MaintainNotCompleteBean>
                                               notCompleteListener,
                                       final OnDataConvertListener<String> statusListener) {
        return RxRestClient.builder()
                .url(Url.SubmitFinishWork)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            String object = jsonObject.getString("data");
                            JSONObject jsonResult = JSONObject.parseObject(object);
                            int status = jsonResult.getInteger("repairStatus");
                            String info = jsonResult.getString("completeInfo");
                            if (info != null) {
                                MaintainNotCompleteBean notCompleteBean
                                        = convertToMaintainNotWork(info);
                                if (notCompleteBean != null) {
                                    if (notCompleteListener != null) {
                                        notCompleteListener.convert(notCompleteBean);
                                    }
                                }
                            }
                            if (status < 4) {
                                return RxRestClient.builder()
                                        .url(Url.GetMyRepairTask)
                                        .params("repairId", repairId)
                                        .params("token", token)
                                        .params("vehicleSeriesId", vehicleSeriesId)
                                        .build()
                                        .onlyPost();
                            } else {
                                return Observable.error(new MyThrowable());
                            }
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            dataListener.convert(convertToBusRepairInfo(object));
                        } else {
                            dataListener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof MyThrowable) {
                            statusListener.convert("");
                        } else {
                            dataListener.error(-1, e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable pickGoods(final String token, final int repairId,
                                final int vehicleSeriesId,
                                String materialApplyList,
                                final OnDataConvertListener<String> pickListener,
                                final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.PickGoods)
                .params("token", token)
                .params("items", materialApplyList)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            if (pickListener != null) {
                                pickListener.convert(ResultMsg);
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            listener.convert(convertToBusRepairInfo(object));
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable commitNotWork(String token, int repairId, String workList,
                                    final OnDataConvertListener<String> listener) {
        return RxRestClient.builder()
                .url(Url.CommitMaintainNotWork)
                .params("repairTaskId", repairId)
                .params("token", token)
                .params("workList", workList)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable cancelFinishWork(final String token, final int repairId,
                                       final int repairTaskId,
                                       final int vehicleSeriesId,
                                       final OnDataConvertListener<String> cancelListener,
                                       final OnDataConvertListener<RepairTaskTypeBean> dataListener) {
        return RxRestClient.builder()
                .url(Url.CancelFinishWork)
                .params("repairId", repairId)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            if (cancelListener != null) {
                                cancelListener.convert("");
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            dataListener.convert(convertToBusRepairInfo(object));
                        } else {
                            cancelListener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        cancelListener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private RepairTaskTypeBean convertToBusRepairInfo(String response) {
        return new ObjConverter<RepairTaskTypeBean>().convert(response
                , new TypeReference<RepairTaskTypeBean>() {
                });
    }

    private List<PickGoods> convertToPickGoods(String response) {
        return new ObjConverter<List<PickGoods>>().convert(response
                , new TypeReference<List<PickGoods>>() {
                });
    }

    private MaintainNotCompleteBean convertToMaintainNotWork(String response) {
        return new ObjConverter<MaintainNotCompleteBean>().convert(response
                , new TypeReference<MaintainNotCompleteBean>() {
                });
    }

    private class MyThrowable extends Throwable {

    }
}
